<!--
 * @Description: 腾讯地图
 * @Author: Caroline
 * @Date: 2024-01-28 19:54:45
 * @LastEditTime: 2024-02-24 10:20:26
 * @LastEditors: Caroline
 * @FilePath: \ronghe-web\src\components\tencent-map\index.vue
-->
<template>
  <div id="tencent-map-box"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted } from "vue";
import useTencentMap from "@/hooks/useTencentMap";

const { tencentMapConfig } = useTencentMap();

onMounted(() => {
  loadMapJs();
});

let map: any = null;

const loadMapJs = () => {
  const mapScriptEl = document.getElementById("tencent_map");
  if (mapScriptEl) {
    initMap();
    return;
  }
  const mapScript = document.createElement("script");
  mapScript.type = "text/javascript";
  mapScript.setAttribute("id", "tencent_map");
  mapScript.src = `https://map.qq.com/api/gljs?v=1.exp&key=${tencentMapConfig.GEO_KEY}`;
  document.body.appendChild(mapScript);
  mapScript.onload = () => {
    //初始化地图
    initMap();
  };
};
const initMap = async () => {
  // 无锡镇坐标
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  let center = new window.TMap.LatLng(31.507189, 119.716453);

  if (map) {
    console.log("map--", map);
    map.destory();
  }
  //定义map变量，调用 TMap.Map() 构造函数创建地图
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  map = new window.TMap.Map(document.getElementById("tencent-map-box"), {
    center, //设置地图中心点坐标
    zoom: 17.2, //设置地图缩放级别
    pitch: 43.5, //设置俯仰角
    rotation: 45, //设置地图旋转角度
    mapStyleId: "style1"
  });

  //绑定点击事件
  map.on("click", function (evt: any) {
    var lat = evt.latLng.getLat().toFixed(6);
    var lng = evt.latLng.getLng().toFixed(6);
    console.log("获取点击的位置坐标=", lat, lng);
  });

  // 设置地图中心
  // const { lat, lng } = await getLocation();
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  // map.setCenter(new window.TMap.LatLng(lat, lng));

  onUnmounted(() => {
    console.log("执行map.destory");
    map.destroy();
  });
};
</script>

<style lang="scss" scoped>
#tencent-map-box {
  width: 100%;
  min-height: 500px;
  height: 100%;
  display: inline-block;
  // 容器可拖放
  resize: both;
  overflow: auto;
}
</style>
